#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>

void display(int number, int flag)
{
    system("clear");
    printf("\n\n\n\n\n\n\n\n\n");
    printf("                    ****************************************\n");
    switch(flag){
    case 0:
            printf("                    *               Welcome !              *\n");
            break;
    case 1:
            printf("                    *           Someone come in !          *\n");
            break;
    case -1:
            printf("                    *           Someone come out !         *\n");
            break;
    case 2:
            printf("                    *        !!! Ghost come out !!!        *\n");
            break;
    }
    printf("                    *                                      *\n");
    printf("                    *      %4d people in the room         *\n", number);
    printf("                    ****************************************\n");
}

int main(int argc, char **argv)
{
	int fd;
	int number = 0;
    int key_value,i,flag = 0;

	fd = open("/dev/button_driver", O_RDONLY);
	if(fd < 0)
	{
		perror("cannot open device button");
		exit(1);
	}

    display(number, flag);

    while(1){
        flag = 0;
        for(i=0;i<2;i++){
            read(fd, &key_value, sizeof(key_value));
            flag = key_value;
        }
        if (flag == 1){
            number++;
            display(number, flag);
        }
        else{
            number--;
            if(number < 0){
                number = 0;
                flag = 2;
            }
            display(number, flag);
        }
    }
	close(fd);
	return 0;

}
